"use strict";
// 限制访问url

$(document).ready(function () {
	chrome.contextMenus.create({
		type: 'normal',
		title: '禁止当前页面访问',
		id: 'restrictUrl',
		contexts: ['all'],
		onclick: genericOnClick
	}, function () {
		console.log('contextMenus are create.id:' + 'restrictUrl' + ',title:' + '禁止当前页面访问');
	});
	
	chrome.contextMenus.create({
		type: 'normal',
		title: '允许当前页面访问',
		id: 'allowUrl',
		contexts: ['all'],
		onclick: genericOnClick
	}, function () {
		console.log('contextMenus are create.id:' + 'allowUrl' + ',title:' + '允许当前页面访问');
	});
	
	chrome.storage.sync.get(['using', 'restrictUrlList'], function(data) {
		var allData = {};
		if (isEmpty(data.using)) {
			allData['using'] = true;
		}
		
		if (isEmpty(data.restrictUrlList) || !isArray(data.restrictUrlList)) {
			allData['restrictUrlList'] = new Array();
		}
		
		if (!isEmptyObj(allData)) {
			chrome.storage.sync.set(allData, function() {
				console.log('init storage');
			});
		}
		
	});
	
	// // test
	// var list = new Array();
	// list.push("www.baidu.com");
	
	// if (containUrl("www.baidu.com", list)) {
	// 	console.log('exist');
	// }
	
	// if (containUrl("www.baidu.co", list)) {
	// 	console.log('exist');
	// }
});

// 菜单点击函数
function genericOnClick(info, tab) {
	//debugLog("selectionText:" + info.selectionText + ",menuItemId:" + info.menuItemId)
	
	// if ('undefined' == typeof info.selectionText) {
	// 	console.log('undefined == typeof info.selectionText');
	// 	return ;
	// } else if (info.selectionText == null) {
	// 	console.log('info.selectionText == null');
	// 	return ;
	// } else {
	// 	if (info.selectionText == "") {
	// 		console.log('info.selectionText == ""');
	// 		return ;
	// 	}
	// }
	
	var testUrl = tab.url;
	
	if (info.menuItemId == 'restrictUrl') {
		chrome.storage.sync.get(['using', 'restrictUrlList'], function(data) {
			if (!containUrl(testUrl, data.restrictUrlList)) {
				data.restrictUrlList.push(testUrl);
				
				chrome.storage.sync.set({'restrictUrlList': data.restrictUrlList}, function() {
					console.log('set storage');
				});
				
				strictUrl(tab.id, testUrl);
				
				// 注入ContentScript
				// chrome.tabs.executeScript(tab.id, {file: "jquery-1.11.2.min.js"}, function() {
				// 	chrome.tabs.executeScript(tab.id, {file: "ContentScript_RestrictUrl.js"}, function() {
				// 		debugLog("excuteScript:ContentScript_RestrictUrl.js");
				// 	});
				// });
			}
		});
	} else if (info.menuItemId == 'allowUrl') {
		chrome.storage.sync.get(['using', 'restrictUrlList'], function(data) {
			console.log("url :" + testUrl);
			
			var tagRestrictUrl = "restricturl=";
			var startIndex = testUrl.indexOf(tagRestrictUrl);
			if (-1 == startIndex) {
				console.log("没有找到'restricturl='标志符");
				return ;
			}

			var orgTestUrl = testUrl.substring(startIndex + tagRestrictUrl.length, testUrl.length);
			
			console.log("orgTestUrl :" + orgTestUrl);
			
			if (removeUrl(orgTestUrl, data.restrictUrlList)) {
				chrome.storage.sync.set({'restrictUrlList': data.restrictUrlList}, function() {
					console.log('set storage');
				});
			}
			
			chrome.tabs.update(tab.id, {url: orgTestUrl}, function() {
				console.log('update');
			});
		});
	}
}

// restrictUrlList列表中包含testUrl,字符串比较相等
function containUrl(testUrl, restrictUrlList) {
	for (var keyUrl of restrictUrlList) {
		if (testUrl == keyUrl) {
			return true;
		}
	}
	
	return false;
}

// restrictUrlList列表中移除testUrl
function removeUrl(testUrl, restrictUrlList) {
	for (var i=0; i<restrictUrlList.length; ++i) {
		console.log(restrictUrlList[i] + " - " + testUrl);
		if (restrictUrlList[i] == testUrl) {
			console.log('remove:' + i);
			restrictUrlList.splice(i, 1);
			return true;
		}
	}
	
	return false;
}


chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
	//console.log('chrome.tabs.onUpdated:' + tab.url + ", changeInfo.status:" + changeInfo.status);
	
	if ('loading' == changeInfo.status) {
		//console.log('tabId:' + tabId);
		//console.log('changeInfo:');
		//console.log(changeInfo);
		
		//console.log('tab:');
		//console.log(tab);
		
		//console.log('chrome.tabs.onUpdated:' + tab.url);
		
		var testUrl = tab.url;
		
		chrome.storage.sync.get(['using', 'restrictUrlList'], function(data) {
			if (data.using) {
				if (containUrl(testUrl, data.restrictUrlList)) {
					// 限制页面访问 - 方案1
					strictUrl(tab.id, testUrl);
					
					// 限制页面访问 - 方案2
					// 注入ContentScript
					// chrome.tabs.executeScript(tab.id, {file: "jquery-1.11.2.min.js"}, function() {
					// 	chrome.tabs.executeScript(tab.id, {file: "ContentScript_RestrictUrl.js"}, function() {
					// 		debugLog("excuteScript:ContentScript_RestrictUrl.js");
					// 	});
					// });
				}
			}
		});
		
		// var tagRestrictUrl = "restricturl=";
		// var startIndex = testUrl.indexOf(tagRestrictUrl);
		// if (-1 != startIndex) {
		// 	// 注入ContentScript
		// 	chrome.tabs.executeScript(tab.id, {file: "jquery-1.11.2.min.js"}, function() {
		// 		chrome.tabs.executeScript(tab.id, {file: "ContentScript_RestrictUrl.js"}, function() {
		// 			console.log("excuteScript:ContentScript_RestrictUrl.js");
		// 		});
		// 	});
		// }

		// if (tab.url.indexOf('https://www.iqiyi.com/v_19r') != -1) {
			
		// 	// chrome.tabs.update(tabId, {url: 'http://www.csdn.net'}, function(tab) {
				
		// 	// });
		// 	chrome.tabs.remove(tabId, function() {
		// 		console.log('close:' + tabId);
		// 	});
		// }
	}
});

function strictUrl(tabId, url) {
	// 限制页面访问 - 方案1
	chrome.tabs.update(tabId, {url: 'http://localhost?restricturl=' + url}, function(){
		console.log('chrome.tabs.update callback');
		
		
	});
}

chrome.tabs.onCreated.addListener(function(tab) {
  	console.log('tabs.onCreated --'
              + ' window: ' + tab.windowId
              + ' tab: '    + tab.id
              + ' index: '  + tab.index
              + ' url: '    + tab.url);
});

// storage监听
chrome.storage.onChanged.addListener(function(changes, namespace) {
	for (var key in changes) {
		var storageChange = changes[key];
		console.log('Storage key "%s" in namespace "%s" changed. ' +
			'Old value was "%o", new value is "%o".',
			key,
			namespace,
			storageChange.oldValue,
			storageChange.newValue);
	}
});

// 消息监听
chrome.extension.onConnect.addListener(function(port) {
	port.onMessage.addListener(function(msg) {
		//debugLog("mtype:" + msg.mtype);
		
		if ('queryWord' == msg.mtype) {

		} else if ('recover' == msg.mtype) {

		}
	});
});



//////////////////////////////////////////////////////
// 功能函数
//////////////////////////////////////////////////////
// 通过id查询url
function getUrlById(allDic, id) {
	for (var i in allDic) {
		if (allDic[i].id == id) {
			return allDic[i].url;
		}
	}
	
	return null;
}

////////////////////////////////////////////////////////////////
// 工具函数
////////////////////////////////////////////////////////////////
//判断字符是否为空的方法
function isEmpty(obj){
	// if(typeof obj == "undefined" || obj == null || obj == ""){
    if(typeof obj == "undefined" || obj == null){
        return true;
    }else{
        return false;
    }
}

function isEmptyObj(obj){
    for(var key in obj) {
		return false;
    }
	
    return true;
}

function isArray(obj){
    if (obj instanceof Array) {
    	return true;
    } else {
    	return false;
    }
}



var g_logCount = 0;
function debugLog(log) {
	var nowTime = new Date().Format("yyyy-MM-dd hh:mm:ss");
	console.log('[' + nowTime + '][' + (++g_logCount) + ']' + log);
}

// 对Date的扩展，将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符， 
// 年(y)可以用 1-4 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) 
// 例子： 
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423 
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18 
Date.prototype.Format = function (fmt) { //author: meizz 
    var o = {
        "M+": this.getMonth() + 1, //月份 
        "d+": this.getDate(), //日 
        "h+": this.getHours(), //小时 
        "m+": this.getMinutes(), //分 
        "s+": this.getSeconds(), //秒 
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度 
        "S": this.getMilliseconds() //毫秒 
    };
    if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
    if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// 参数格式化 String.format("look at {0}", jack)
String.format = function() {
    if (arguments.length == 0)
        return null;
    var str = arguments[0];
    for ( var i = 1; i < arguments.length; i++) {
        var re = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
        str = str.replace(re, arguments[i]);
    }
    return str;
};

// 调用百度api翻译单词
function queryWordByAPI(query, callback) {
	var appid = '20190903000331677';
	var key = 'JQZe1KhuIIyG7XUFEhJO';
	var salt = (new Date).getTime();
	//var query = 'apple';
	// 多个query可以用\n连接  如 query='apple\norange\nbanana\npear'
	var from = 'en';
	var to = 'zh';
	var str1 = appid + query + salt +key;
	var sign = MD5(str1);
	
	var url = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=" + query + "&appid=" + appid + "&salt=" + salt + "&from=" + from + "&to=" + to + "&sign=" + sign;
	
	$.get(url, function (result) {
		//console.log(result);
		callback(result);
	});
}